from app.db.models.user import User
from sqlalchemy.orm import Session
import uuid
from app.db.models.user import User, Group, FriendGroup
from datetime import datetime

class UserService:
    @staticmethod
    def get_user_by_email(db: Session, email: str) -> User | None:
        return db.query(User).filter(User.email == email).first()
    
    @staticmethod
    def get_user_by_userid(db: Session, userid: str) -> User | None:
        return db.query(User).filter(User.userid == userid).first()
    
    @staticmethod
    def get_user_by_id(db: Session, id: int) -> User | None:
        return db.query(User).filter(User.id == id).first()
    
    @staticmethod
    def create_default_groups(db: Session, user_id: int):
        """为用户创建默认分组"""
        # 预设分组列表
        default_groups = [
            {"name": "我的好友", "is_default": True},
            {"name": "朋友", "is_default": False},
            {"name": "家人", "is_default": False},
            {"name": "同学", "is_default": False}
        ]

        # 先检查这些分组模板是否存在，不存在则创建
        for group_info in default_groups:
            group = db.query(Group).filter(Group.name == group_info["name"]).first()
            if not group:
                group = Group(
                    name=group_info["name"],
                    is_default=group_info["is_default"]
                )
                db.add(group)
                db.flush()  # 获取group.id
            
            # 为用户创建对应的分组
            user_group = FriendGroup(
                user_id=user_id,
                group_id=group.id
            )
            db.add(user_group)
        try:
            db.commit()
        except Exception as e:
            db.rollback()
            raise e

    @staticmethod
    def create_user(
        db: Session, 
        email: str, 
        password: str, 
        nickname: str,
        sex: int = 0  # 添加默认值
    ) -> User:
        try:
            user = User(
                userid=str(uuid.uuid4()),  # 设置业务ID
                email=email,
                password=password,
                nickname=nickname,
                sex=sex,
                avatar="",  # 设置默认值
                online=0,   # 设置默认值
                device_fingerprint="",  # 设置默认值
                created_at=datetime.now()  # 设置创建时间
            )
            db.add(user)
            db.flush()  # 获取user.id
            
            # 为用户创建默认分组
            UserService.create_default_groups(db, user.id)
            
            db.commit()
            db.refresh(user)
            return user
        except Exception as e:
            db.rollback()
            raise e